package com.faintlight.config;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class WeChatConfig {

    private static final Logger logger = LoggerFactory.getLogger(WeChatConfig.class);

    @Bean
    public WxMpService wxMpService(WxMpProperties properties) {
        logger.info("✅ 初始化微信服务");
        WxMpService mpService = new WxMpServiceImpl();
        Map<String, WxMpConfigStorage> configMap = new HashMap<>();

        properties.getApps().forEach((name, app) -> {
            logger.info("📦 配置小程序: {}", name);
            WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
            config.setAppId(app.getAppid());
            config.setSecret(app.getSecret());
            config.setToken(app.getToken());
            config.setAesKey(app.getAesKey());
            configMap.put(name, config);
        });

        mpService.setMultiConfigStorages(configMap);
        logger.info("✅ 微信服务初始化完成，支持 {} 个小程序", configMap.size());
        return mpService;
    }
}
